<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>👥 用户管理</h2>
        <p class="page-description">普通用户管理、状态控制、操作日志</p>
      </div>
      <div class="header-actions">
        <button @click="refreshUsers" class="btn-secondary" :disabled="isLoading">
          🔄 {{ isLoading ? '加载中...' : '刷新' }}
        </button>
      </div>
    </div>

    <!-- 用户统计概览 -->
    <div class="stats-overview">
      <div class="stat-card">
        <div class="stat-icon">👤</div>
        <div class="stat-info">
          <div class="stat-value">{{ userStats.total }}</div>
          <div class="stat-label">普通用户总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">⏰</div>
        <div class="stat-info">
          <div class="stat-value">{{ userStats.todayLogin }}</div>
          <div class="stat-label">今日登录用户</div>
        </div>
      </div>
    </div>

    <!-- 用户管理内容 -->
    <div class="user-content">
      <div class="content-header">
        <div class="filters">
          <div class="filter-group">
            <label>用户状态:</label>
            <select v-model="filters.status" @change="applyFilters">
              <option value="all">全部状态</option>
              <option value="1">活跃</option>
              <option value="0">已封禁</option>
            </select>
          </div>
        </div>
        <div class="search-box">
          <input
              v-model="filters.search"
              @input="applyFilters"
              placeholder="搜索用户名、手机号..."
              type="text"
          >
        </div>
      </div>

      <!-- 用户表格 -->
      <div class="user-table-container">
        <table class="user-table">
          <thead>
          <tr>
            <th>用户信息</th>
            <th>状态</th>
            <th>注册时间</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td class="user-info">
              <div class="user-avatar">
                {{ user.username?.charAt(0)?.toUpperCase() || 'U' }}
              </div>
              <div class="user-details">
                <div class="user-name">{{ user.username || `用户${user.phone}` }}</div>
                <div class="user-phone" v-if="user.phone">{{ user.phone }}</div>
              </div>
            </td>
            <td>
                <span class="status-badge" :class="user.status === 1 ? 'active' : 'inactive'">
                  {{ getStatusText(user.status) }}
                </span>
            </td>
            <td class="time-info">
              {{ formatTime(user.loginTime) }}
            </td>
            <td class="actions">
              <button
                  @click="toggleUserStatus(user)"
                  class="btn-action"
                  :class="user.status === 1 ? 'deactivate' : 'activate'"
                  :title="user.status === 1 ? '封禁用户' : '解封用户'"
              >
                {{ user.status === 1 ? '⏸️' : '▶️' }}
              </button>
              <button
                  @click="deleteUser(user)"
                  class="btn-action delete"
                  title="删除用户"
              >
                🗑️
              </button>
            </td>
          </tr>
          </tbody>
        </table>

        <!-- 空状态 -->
        <div v-if="filteredUsers.length === 0 && !isLoading" class="empty-state">
          <div class="empty-icon">🔍</div>
          <h3>未找到用户</h3>
          <p v-if="filteredUsersByManager.length === 0">暂无您管理的用户数据（user.manager ≠ 当前管理员手机号）</p>
          <p v-else>暂无匹配搜索条件的用户</p>
          <button @click="clearFilters" class="btn-primary">清除筛选条件</button>
          <button @click="refreshUsers" class="btn-secondary" style="margin-left: 10px;">
            刷新数据
          </button>
        </div>
      </div>
    </div>

    <!-- 操作日志 -->
    <div class="operation-logs">
      <div class="section-header">
        <h3>📋 操作日志</h3>
        <button @click="refreshLogs" class="btn-secondary">
          🔄 刷新日志
        </button>
      </div>
      <div class="logs-list">
        <div v-for="log in operationLogs" :key="log.id" class="log-item" :class="log.type">
          <div class="log-icon">{{ getLogIcon(log.type) }}</div>
          <div class="log-content">
            <div class="log-title">{{ log.action }}</div>
            <div class="log-details">
              <span class="log-user">操作人: {{ log.operator }}</span>
              <span class="log-time">{{ formatTime(log.time) }}</span>
            </div>
            <div class="log-message">{{ log.message }}</div>
            <div class="log-target" v-if="log.target">目标: {{ log.target }}</div>
          </div>
        </div>
        <div v-if="operationLogs.length === 0" class="no-logs">
          <div class="no-logs-icon">📝</div>
          <p>暂无操作记录</p>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { userService } from '@/api/userService'
import { useAuthStore } from '@/stores/auth'
// 导入userAPI，用于获取保存的用户信息（关键）
import { userAPI } from '@/api/userAPI'

export default {
  name: 'UserManagement',
  setup() {
    const authStore = useAuthStore()

    // 响应式数据
    const users = ref([])
    const isLoading = ref(false)
    const operationLogs = ref([])

    // 筛选条件
    const filters = ref({
      status: 'all',
      search: ''
    })

    // 🔥 核心优化：100%确保获取「保存的管理员phone」，优先用userAPI（你登录时保存的信息）
    const filteredUsersByManager = computed(() => {
      // 方式1：从userAPI获取（你登录时保存到localStorage的用户信息，最准确）
      const currentUser = userAPI.getCurrentUser()
      const currentManagerPhone = currentUser?.phone

      // 方式2：备用方案（从authStore获取，防止方式1失效）
      const backupManagerPhone = authStore.user?.phone
      const finalManagerPhone = currentManagerPhone || backupManagerPhone

      // 调试日志：清晰展示关键数据，便于定位问题
      console.log('📱 保存的管理员手机号（localStorage）:', currentManagerPhone)
      console.log('📱 备用管理员手机号（authStore）:', backupManagerPhone)
      console.log('📱 最终用于匹配的手机号:', finalManagerPhone)
      console.log('📊 后端返回的所有用户数据:', users.value)

      // 无手机号则返回空
      if (!finalManagerPhone) {
        console.error('⚠️ 未获取到保存的管理员手机号')
        return []
      }

      // 核心筛选逻辑：user.role是普通用户 + user.manager === 保存的管理员手机号
      const matchedUsers = users.value.filter(user => {
        // 打印每个用户的匹配关键信息
        console.log(`🔍 用户${user.id || '未知'}: role=${user.role}, manager=${user.manager}, 是否匹配=${user.role === 'USER' && user.manager === finalManagerPhone}`)
        return user.role === 'USER' && user.manager === finalManagerPhone
      })

      console.log(`✅ 匹配成功的用户数: ${matchedUsers.length}（条件：user.manager = ${finalManagerPhone}）`)
      return matchedUsers
    })

    // 用户统计（基于匹配后的用户）
    const userStats = computed(() => {
      const total = filteredUsersByManager.value.length
      const todayLogin = filteredUsersByManager.value.filter(u => {
        if (!u.loginTime) return false
        try {
          const loginDate = new Date(u.loginTime).toDateString()
          const today = new Date().toDateString()
          return loginDate === today
        } catch {
          return false
        }
      }).length
      return { total, todayLogin }
    })

    // 最终筛选结果（匹配后 + 状态 + 搜索）
    const filteredUsers = computed(() => {
      return filteredUsersByManager.value.filter(user => {
        // 状态筛选
        if (filters.value.status !== 'all' && user.status.toString() !== filters.value.status) {
          return false
        }

        // 搜索筛选
        if (filters.value.search) {
          const searchTerm = filters.value.search.toLowerCase()
          return (
              (user.username && user.username.toLowerCase().includes(searchTerm)) ||
              (user.phone && user.phone.includes(searchTerm))
          )
        }

        return true
      })
    })

    // 获取用户列表：适配后端返回格式（无code，用message和data判断）
    const fetchUsers = async () => {
      isLoading.value = true
      try {
        console.log('🔄 开始获取用户列表...')
        const result = await userService.getUsersList()
        console.log('📨 后端返回原始结果:', result)

        // 🔥 核心修复：适配后端实际返回格式 { message: '查询成功', data: 数组 }
        // 成功条件：result存在 + message为"查询成功" + data是数组
        if (result && result.message === '查询成功' && Array.isArray(result.data)) {
          users.value = result.data || []
          console.log('✅ 用户列表获取成功，后端总返回数:', users.value.length)

          // 打印所有用户关键字段，便于调试匹配
          console.log('📋 所有用户的manager/role/phone字段:', users.value.map(u => ({
            id: u.id,
            manager: u.manager,
            role: u.role,
            phone: u.phone
          })))

          // 若匹配数为0，提示可能原因
          if (filteredUsersByManager.value.length === 0) {
            const finalManagerPhone = userAPI.getCurrentUser()?.phone || authStore.user?.phone
            console.log('ℹ️ 无匹配用户可能原因：1. 普通用户的manager字段不等于', finalManagerPhone, ' 2. 无普通用户数据')
            addOperationLog('info', '获取用户列表', '系统', `无匹配user.manager=${finalManagerPhone}的普通用户`)
          } else {
            addOperationLog('success', '获取用户列表', '系统', `成功加载${filteredUsersByManager.value.length}个管理用户`)
          }
        } else {
          console.error('❌ 获取用户列表失败:', result?.message || '后端返回格式异常')
          addOperationLog('error', '获取用户列表', '系统', result?.message || '获取失败')
        }
      } catch (error) {
        console.error('💥 获取用户列表异常:', error)
        addOperationLog('error', '获取用户列表', '系统', '网络错误')
      } finally {
        isLoading.value = false
      }
    }

    // 刷新用户列表
    const refreshUsers = () => {
      console.log('🔄 手动刷新用户列表')
      fetchUsers()
    }

    // 刷新日志
    const refreshLogs = () => {
      operationLogs.value = [...operationLogs.value]
    }

    // 切换用户状态：适配后端返回格式
    const toggleUserStatus = async (user) => {
      if (!confirm(`确定要${user.status === 1 ? '封禁' : '解封'}用户 "${user.username || user.phone}" 吗？`)) {
        return
      }

      try {
        const result = await userService.alterStatus(user.phone)
        // 适配后端：用message判断成功（例："状态修改成功"）
        if (result && result.message === '状态修改成功') {
          const idx = users.value.findIndex(u => u.phone === user.phone && u.role === 'USER')
          if (idx !== -1) users.value[idx].status = user.status === 1 ? 0 : 1
          const action = user.status === 1 ? '封禁' : '解封'
          addOperationLog('success', '状态修改', user.username || user.phone, `${action}成功`)
          alert(`${action}成功`)
        } else {
          alert(result?.message || '操作失败')
        }
      } catch (error) {
        console.error('修改状态失败:', error)
        alert('操作失败，请重试')
      }
    }

    // 删除用户：适配后端返回格式
    const deleteUser = async (user) => {
      if (!confirm(`确定要删除用户 "${user.username || user.phone}" 吗？此操作不可恢复。`)) {
        return
      }

      try {
        const result = await userService.deleteUser(user.phone)
        // 适配后端：用message判断成功（例："删除成功"）
        if (result && result.message === '删除成功') {
          alert('删除成功')
          users.value = users.value.filter(u => !(u.phone === user.phone && u.role === 'USER'))
          addOperationLog('warning', '删除用户', user.username || user.phone, '已删除')
        } else {
          alert(result?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        alert('操作失败，请重试')
      }
    }

    // 添加操作日志
    const addOperationLog = (type, action, target, message) => {
      const operator = userAPI.getCurrentUser()?.phone || '未知管理员'
      operationLogs.value.unshift({
        id: Date.now(),
        action,
        operator,
        target,
        time: new Date().toLocaleString('zh-CN'),
        type,
        message
      })
      if (operationLogs.value.length > 100) operationLogs.value = operationLogs.value.slice(0, 100)
    }

    // 工具函数
    const getStatusText = (status) => status === 1 ? '活跃' : '已封禁'
    const getLogIcon = (type) => ({ success: '✅', error: '❌', warning: '⚠️', info: 'ℹ️' }[type] || '📝')
    const formatTime = (timeString) => {
      if (!timeString) return '未知'
      try {
        return new Date(timeString).toLocaleString('zh-CN')
      } catch {
        return timeString
      }
    }

    // 筛选相关
    const applyFilters = () => {}
    const clearFilters = () => {
      filters.value = { status: 'all', search: '' }
    }

    // 监听登录状态变化，刷新用户列表
    watch(
        () => [authStore.user, userAPI.getCurrentUser()],
        ([newAuthUser, newLocalUser]) => {
          if (newAuthUser || newLocalUser) {
            console.log('👤 登录状态变化，刷新用户列表')
            setTimeout(fetchUsers, 500)
          }
        },
        { deep: true }
    )

    // 初始化加载
    onMounted(() => {
      console.log('🚀 用户管理页面初始化')
      fetchUsers()
      addOperationLog('info', '页面访问', '用户管理', '进入管理页面')
    })

    return {
      users,
      userStats,
      filteredUsers,
      filteredUsersByManager,
      isLoading,
      filters,
      operationLogs,
      refreshUsers,
      refreshLogs,
      toggleUserStatus,
      deleteUser,
      getStatusText,
      getLogIcon,
      formatTime,
      applyFilters,
      clearFilters
    }
  }
}
</script>

<style scoped>
/* 删除农场信息相关的CSS样式 */
.farm-info,
.farm-name,
.farm-location {
  display: none;
}

/* 调整表格列宽：适配移除角色列后的布局 */
.user-table th:nth-child(2),
.user-table td:nth-child(2) {
  width: 100px;
}

.user-table th:nth-child(3),
.user-table td:nth-child(3) {
  width: 180px;
}

/* 其他样式保持不变 */
.user-management {
  padding: 1rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e2e8f0;
}

.header-content h2 {
  margin: 0 0 0.5rem 0;
  color: #2d3748;
  font-size: 1.75rem;
}

.page-description {
  margin: 0;
  color: #718096;
  font-size: 1rem;
}

.header-actions {
  display: flex;
  gap: 1rem;
}

.btn-primary {
  background: #48bb78;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.btn-primary:hover:not(:disabled) {
  background: #3ca56c;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

.btn-secondary {
  background: #e2e8f0;
  color: #4a5568;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.btn-secondary:hover:not(:disabled) {
  background: #cbd5e0;
}

.btn-secondary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 统计概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 1rem;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 2rem;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2d3748;
  margin-bottom: 0.25rem;
}

.stat-label {
  font-size: 0.9rem;
  color: #718096;
}

/* 用户内容区域 */
.user-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
  overflow: hidden;
}

.content-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.filters {
  display: flex;
  gap: 1.5rem;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter-group label {
  font-size: 0.9rem;
  color: #4a5568;
  font-weight: 500;
}

.filter-group select {
  padding: 0.5rem;
  border: 1px solid #cbd5e0;
  border-radius: 4px;
  background: white;
  min-width: 120px;
}

.search-box input {
  padding: 0.5rem 1rem;
  border: 1px solid #cbd5e0;
  border-radius: 4px;
  width: 250px;
}

/* 用户表格 */
.user-table-container {
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th {
  background: #f7fafc;
  padding: 1rem;
  text-align: left;
  font-weight: 600;
  color: #4a5568;
  border-bottom: 1px solid #e2e8f0;
}

.user-table td {
  padding: 1rem;
  border-bottom: 1px solid #e2e8f0;
}

.user-table tr:hover {
  background: #f7fafc;
}

/* 用户信息列 */
.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1rem;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 0.25rem;
}

.user-phone {
  font-size: 0.8rem;
  color: #a0aec0;
}

/* 状态列 */
.status-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.status-badge.active {
  background: #c6f6d5;
  color: #276749;
}

.status-badge.inactive {
  background: #fed7d7;
  color: #c53030;
}

/* 时间信息列 */
.time-info {
  color: #718096;
  font-size: 0.9rem;
  white-space: nowrap;
}

/* 操作列 */
.actions {
  display: flex;
  gap: 0.5rem;
}

.btn-action {
  background: none;
  border: none;
  padding: 0.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s;
}

.btn-action:hover:not(:disabled) {
  background: #e2e8f0;
}

.btn-action:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-action.delete:hover {
  background: #fed7d7;
}

/* 空状态 */
.empty-state {
  padding: 3rem;
  text-align: center;
  color: #718096;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  margin: 0 0 0.5rem 0;
  color: #4a5568;
}

.empty-state p {
  margin: 0 0 1.5rem 0;
}

/* 操作日志 */
.operation-logs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  color: #2d3748;
}

.logs-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 1rem;
}

.log-item {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  margin-bottom: 0.75rem;
  background: #f7fafc;
  border-radius: 6px;
  border-left: 4px solid #cbd5e0;
}

.log-item.success {
  border-left-color: #48bb78;
  background: #f0fff4;
}

.log-item.error {
  border-left-color: #e53e3e;
  background: #fff5f5;
}

.log-item.warning {
  border-left-color: #f59e0b;
  background: #fffbeb;
}

.log-icon {
  font-size: 1.2rem;
  flex-shrink: 0;
}

.log-content {
  flex: 1;
}

.log-title {
  font-weight: 500;
  margin-bottom: 0.25rem;
  color: #2d3748;
}

.log-details {
  display: flex;
  gap: 1rem;
  font-size: 0.8rem;
  color: #718096;
  margin-bottom: 0.25rem;
}

.log-message {
  font-size: 0.9rem;
  color: #4a5568;
  margin-bottom: 0.25rem;
}

.log-target {
  font-size: 0.8rem;
  color: #718096;
  font-style: italic;
}

.no-logs {
  text-align: center;
  padding: 2rem;
  color: #718096;
}

.no-logs-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-left: 4px solid #48bb78;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

.loading-text {
  color: #718096;
  font-size: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 1rem;
  }

  .content-header {
    flex-direction: column;
    align-items: stretch;
  }

  .filters {
    flex-direction: column;
    gap: 1rem;
  }

  .search-box input {
    width: 100%;
  }
}
</style>